package models

import (
	"time"

	"gorm.io/gorm"
)

// Category 分类模型（重构后统一命名）
type Category struct {
	ID           int            `json:"id" gorm:"primaryKey;autoIncrement"`
	Code         *string        `json:"code" gorm:"type:varchar(50);uniqueIndex;comment:分类代码"`
	Name         string         `json:"name" gorm:"type:varchar(100);not null"`
	Description  *string        `json:"description" gorm:"type:text"`
	Icon         *string        `json:"icon" gorm:"type:varchar(255)"`
	DisplayOrder int            `json:"display_order" gorm:"default:0;index"`
	ParentID     *int           `json:"parent_id" gorm:"index"`
	Status       int            `json:"status" gorm:"default:1;index;comment:状态 1-启用 0-禁用"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联关系
	Parent   *Category  `json:"parent,omitempty" gorm:"foreignKey:ParentID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
	Children []Category `json:"children,omitempty" gorm:"foreignKey:ParentID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`

	// 多对多关联关系
	Pages []Page `json:"pages,omitempty" gorm:"many2many:page_categories;"`
	Items []Item `json:"items,omitempty" gorm:"many2many:category_items;"`
}

// GormCategory 保持向后兼容的别名
type GormCategory = Category

// TableName 指定表名
func (Category) TableName() string {
	return "categories"
}

// BeforeCreate GORM钩子 - 创建前
func (c *Category) BeforeCreate(tx *gorm.DB) error {
	// 可以在这里添加创建前的逻辑
	return nil
}

// BeforeUpdate GORM钩子 - 更新前
func (c *Category) BeforeUpdate(tx *gorm.DB) error {
	// 可以在这里添加更新前的逻辑
	return nil
}

// CreateCategoryRequest 创建分类请求结构体
type CreateCategoryRequest struct {
	Name         string  `json:"name" binding:"required"`
	Description  *string `json:"description"`
	Icon         *string `json:"icon"`
	DisplayOrder int     `json:"display_order"`
	ParentID     *int    `json:"parent_id"`
	Status       int     `json:"status"`
	// 关联关系
	PageIDs []int `json:"page_ids,omitempty"` // 要关联的页面ID数组
	ItemIDs []int `json:"item_ids,omitempty"` // 要关联的项目ID数组
}

// ToCategory 将请求转换为Category模型
func (req *CreateCategoryRequest) ToCategory() *Category {
	return &Category{
		Name:         req.Name,
		Description:  req.Description,
		Icon:         req.Icon,
		DisplayOrder: req.DisplayOrder,
		ParentID:     req.ParentID,
		Status:       req.Status,
	}
}
